package com.surfilter.modules.role.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.surfilter.modules.role.dao.RoleDao;
import com.surfilter.modules.role.model.ActionModel;
import com.surfilter.modules.role.model.ModuleModel;
import com.surfilter.modules.role.model.PermissionModel;
import com.surfilter.modules.role.model.RoleModel;
import com.surfilter.modules.role.model.UserModel;
import com.surfilter.modules.role.service.RoleMgr;
import com.surfilter.modules.user.dao.PermissionDao;
import com.surfilter.platform.base.exception.CustomException;
import com.surfilter.platform.base.model.ActionPermission;
import com.surfilter.platform.base.model.Constants;
import com.surfilter.platform.base.model.PageInfo;
import com.surfilter.platform.base.model.ParameterClassType;
import com.surfilter.platform.base.model.ParameterInfo;
import com.surfilter.platform.base.model.ParameterMapper;
import com.surfilter.platform.base.model.PermissionMethodType;
import com.surfilter.platform.base.service.ServiceBase;
import com.surfilter.platform.base.service.ServiceContext;

@Service(value=Constants.SERVICE_ROLE)
public class RoleMgrImpl extends ServiceBase  implements RoleMgr {
	
	@Resource
	private RoleDao roleDao;
	@Resource
	private PermissionDao permissionDao;
	
	@ActionPermission(actionName = "addRole",remark = "添加角色", permission = PermissionMethodType.MODULE)
	@ParameterMapper({
		@ParameterInfo(mapName = "actionIds", componentType = Integer.class, index = 1, mapType = ParameterClassType.ARRAY),
		@ParameterInfo(mapName = "moduleIds", componentType = Integer.class, index = 2, mapType = ParameterClassType.ARRAY),
		@ParameterInfo(mapName = "userIds", componentType = Integer.class, index = 3, mapType = ParameterClassType.ARRAY)})
	@Transactional(value="sufilter")
	public int addRole(RoleModel model,List<Integer> actions, List<Integer> modules,List<Integer> users,HttpServletRequest request) {
 		RoleModel rs = roleDao.getRoleByName(model);
		if(rs != null){
			throw new CustomException("角色名重复，修改角色名后添加。");
		}
		int sessionUserId = ServiceContext.getUserIdInSession(request);
		model.setCreateTime(new Date());
		model.setCreateUser(sessionUserId);
		model.setUpdateTime(new Date());
		model.setUpdateUser(sessionUserId);
		int roleId = roleDao.addRole(model);
		List<PermissionModel> pList = new ArrayList<PermissionModel>();
		if(modules != null){
			for(int id : modules){
				PermissionModel pModel = new PermissionModel();
				pModel.setCreateTime(new Date());
				pModel.setCreateUser(sessionUserId);
				pModel.setFunctionId(id);
				pModel.setFunctionType(1);
				pModel.setOwnerId(roleId);
				pModel.setOwnerType(2);
				pList.add(pModel);
			}
		}
		if(actions != null){
			for(int id : actions){
				PermissionModel pModel = new PermissionModel();
				pModel.setCreateTime(new Date());
				pModel.setCreateUser(sessionUserId);
				pModel.setFunctionId(id);
				pModel.setFunctionType(2);
				pModel.setOwnerId(roleId);
				pModel.setOwnerType(2);
				pList.add(pModel);
			}
		}
		if(pList.size() > 0){
			permissionDao.addBatchPermission(pList);
		}
		if(users != null){
			roleDao.addAllRoleUsers(users, roleId, sessionUserId, new Date());
		}
		return roleId;
		
	}

	@ActionPermission(actionName = "chgRole",remark = "修改角色信息", permission = PermissionMethodType.MODULE)
	@ParameterMapper({
		@ParameterInfo(mapName = "id", index = 0),
//		@ParameterInfo(mapName = "roleParams", componentType = RoleModel.class, index = 1, mapType = ParameterClassType.JSONOBJECT),
		@ParameterInfo(mapName = "actionIds", componentType = Integer.class, index = 2, mapType = ParameterClassType.ARRAY),
		@ParameterInfo(mapName = "moduleIds", componentType = Integer.class, index = 3, mapType = ParameterClassType.ARRAY),
		@ParameterInfo(mapName = "userIds", componentType = Integer.class, index = 4, mapType = ParameterClassType.ARRAY)
		}
	)
	@Transactional(value="sufilter")
	public void chgRole(int roleId, RoleModel model,List<Integer> actions, List<Integer> modules,List<Integer> users,HttpServletRequest request) {
// 		RoleModel rs = roleDao.getRoleByName(model);
//		if(rs != null){
//			throw new CustomException("角色名重复，修改角色名后添加。");
//		}
		int sessionUserId = ServiceContext.getUserIdInSession(request);
		model.setCreateTime(new Date());
		model.setCreateUser(sessionUserId);
		model.setUpdateTime(new Date());
		model.setUpdateUser(sessionUserId);
		//删除所有与本角色相关
		delRoleOthers(roleId);
		modifyRoleInfo(roleId, model);
		List<PermissionModel> pList = new ArrayList<PermissionModel>();
		if(modules != null){
			for(int id : modules){
				PermissionModel pModel = new PermissionModel();
				pModel.setCreateTime(new Date());
				pModel.setCreateUser(sessionUserId);
				pModel.setFunctionId(id);
				pModel.setFunctionType(1);
				pModel.setOwnerId(roleId);
				pModel.setOwnerType(2);
				pList.add(pModel);
			}
		}
		if(actions != null){
			for(int id : actions){
				PermissionModel pModel = new PermissionModel();
				pModel.setCreateTime(new Date());
				pModel.setCreateUser(sessionUserId);
				pModel.setFunctionId(id);
				pModel.setFunctionType(2);
				pModel.setOwnerId(roleId);
				pModel.setOwnerType(2);
				pList.add(pModel);
			}
		}
		if(pList.size() > 0){
			permissionDao.addBatchPermission(pList);
		}
		if(users != null){
			roleDao.addAllRoleUsers(users, roleId, sessionUserId, new Date());
		}
	}

	private void delRoleOthers(int roleId) {
		permissionDao.delPermissionByRoleId(roleId);
		roleDao.delRoleUsersByRoleID(roleId);
	}

	private void modifyRoleInfo(int roleId, RoleModel model) {
		roleDao.chgRole(model, roleId);
	}

	@Override
	public void delRole(RoleModel model, HttpServletRequest request) {
		// TODO Auto-generated method stub

	}

	@ActionPermission(actionName = "getRoles",remark = "获取所有角色", permission = PermissionMethodType.MODULE)
	public List<RoleModel> getRoles(RoleModel model, HttpServletRequest request) {
		PageInfo pageInfo = PageInfo.getPageInfo(request);
		return roleDao.getRoles(model,pageInfo);
	}

	@ActionPermission(actionName = "getRolesCount",remark = "获取角色数量", permission = PermissionMethodType.NONE)
	public int getRolesCount(RoleModel model){
		return roleDao.getRolesCount(model);
	}
	
	@Transactional(value="sufilter")
	@ActionPermission(actionName = "delRoles",remark = "删除角色", permission = PermissionMethodType.MODULE)
	@ParameterMapper({ @ParameterInfo(mapName = "roleIds", componentType = Integer.class, index = 0, mapType = ParameterClassType.ARRAY) })
	public boolean delRoles(List<Integer> roleIds) {
		roleDao.delRoles(roleIds);
		permissionDao.delPermissionByRoleIds(roleIds);
		return true;
	}

	@ActionPermission(actionName = "getRole",remark = "通过角色id获取角色",permission = PermissionMethodType.MODULE)
	@ParameterMapper( 
			@ParameterInfo(mapName = "roleId", index = 0))
	public RoleModel getRole(int roleId){
		return roleDao.getRoleById(roleId);
	}
	
	@ActionPermission(actionName = "getModulesAndActions",remark = "获取模块和Action", permission = PermissionMethodType.MODULE)
	public List<ModuleModel> getModulesAndActions(HttpServletRequest request) {
		// TODO Auto-generated method stub
		List<ModuleModel> moduleModels = roleDao.getAllValidModules();
		for(ModuleModel model : moduleModels){
			List<ActionModel> tempActions = roleDao.getActionsOfModule(model.getId());
			model.setActionModels(tempActions);
		}
		return moduleModels;
	}
	
	@ActionPermission(actionName = "getModulesAndActionsByRoleId",remark = "获取角色对应模块action", permission = PermissionMethodType.MODULE)
	@ParameterMapper( 
			@ParameterInfo(mapName = "roleId", index = 0))
	public List<ModuleModel> getModulesAndActionsById(int roleId) {
		List<ModuleModel> moduleModels = roleDao.getAllValidModules();
		List<ActionModel> actionModelList = roleDao.getValidActionsByRole(new RoleModel(roleId));
		List<ModuleModel> moduleModelList = roleDao.getValidModulesByRole(new RoleModel(roleId));
		for(ModuleModel model : moduleModels){
			model.setChecked(false);
			List<ActionModel> tempActions = roleDao.getActionsOfModule(model.getId());
			
			for(ActionModel action : tempActions){
				action.setChecked(false);
				if(isRoleHasPermission(action, actionModelList)){
					action.setChecked(true);
				}
			}
			if(isRoleHasPermission(model, moduleModelList)){
				model.setChecked(true);
			}
			model.setActionModels(tempActions);
		}
		
		
		return moduleModels;
	}

	private boolean isRoleHasPermission(ActionModel action, List<ActionModel> actionModelList) {
		for(ActionModel actionModel : actionModelList){
			int actionId = actionModel.getId();
			if(actionId == action.getId()){
				return true;
			}
		}
		return false;
	}
	
	private boolean isRoleHasPermission(ModuleModel module, List<ModuleModel> moduleModelList) {
		for(ModuleModel moduleModel : moduleModelList){
			int moduleId = moduleModel.getId();
			if(moduleId == module.getId()){
				return true;
			}
		}
		return false;
	}

	@ActionPermission(actionName = "getUsersByRoleId",remark = "获取角色下所有用户", permission = PermissionMethodType.NONE)
	@ParameterMapper( 
			@ParameterInfo(mapName = "roleId", index = 0))
	public List<UserModel> getUsersByRoleId(int roleId) {
		List<UserModel> list = roleDao.getUsersByRoleId(roleId);
		return list;
	}
	
	@ActionPermission(actionName = "getExtraUsersByRoleId",remark = "获取角色下所有用户", permission = PermissionMethodType.NONE)
	@ParameterMapper( 
			@ParameterInfo(mapName = "roleId", index = 0))
	public List<UserModel> getExtraUsersByRoleId(int roleId) {
		List<UserModel> list = roleDao.getExtraUsersByRoleId(roleId);
		return list;
	}
}
